package com.idfsgm;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.idfsgm.R;
import com.example.idfsgm.R.layout;
import com.example.idfsgm.R.menu;
import com.example.idfsgm.util.NotEnoughParticipantsException;

import datatypes.Assignment;
import datatypes.Duty;
import datatypes.DutyDate;
import datatypes.GuardDuty;
import datatypes.KitchenDuty;
import datatypes.Service;
import datatypes.Soldier;
import datatypes.Team;

import Utils.SavingAndLoadingCenter;
import Utils.ServiceManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.TimePicker;

public class ServiceSettings extends Activity {

	public TimePicker fromTime;
	public TimePicker toTime;
	public DatePicker fromDate;
	public DatePicker toDate;

	public ListView hourList;
	public ListView SoldierList;

	public Button btnCheckAll;
	public Button btnClearAll;
	public Button btnAssign;

	private int hour;
	private int minute;
	private TimePickerDialog.OnTimeSetListener timePickerListener;
	static final int TIME_DIALOG_ID = 999;

	private final Calendar calendar = Calendar.getInstance();
	private TabHost OptionTabHost;
	private Map<Integer, Soldier> soldierMap;
	private List<Soldier> chosenSoldiers;
	private List<Duty> dutyList;

	private int dutyType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_service_settings);

		setDutyType();
		setupWidgets();
		setCurrentTimeOnView();
		setupTabHost();
		setupTabFunctionality();

		timePickerListener = new TimePickerDialog.OnTimeSetListener() {
			public void onTimeSet(TimePicker view, int selectedHour,
					int selectedMinute) {
				hour = selectedHour;
				minute = selectedMinute;

				// set current time into time picker
				fromTime.setCurrentHour(hour);
				fromTime.setCurrentMinute(minute);

				toTime.setCurrentHour(hour);
				toTime.setCurrentMinute(minute);

			}
		};

	}

	private void setDutyType() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			dutyType = extras.getInt("TYPE");
		}
	}

	private void setupWidgets() {
		fromTime = (TimePicker) findViewById(R.id.FromTimePicker);
		toTime = (TimePicker) findViewById(R.id.ToTimePicker);

		fromDate = (DatePicker) findViewById(R.id.FromDatePicker);
		toDate = (DatePicker) findViewById(R.id.ToDatePicker);

		hourList = (ListView) findViewById(R.id.hourList);
		SoldierList = (ListView) findViewById(R.id.soldierForDutyList);

		btnCheckAll = (Button) findViewById(R.id.btnCheckAll);
		btnClearAll = (Button) findViewById(R.id.btnClearAll);
		btnAssign = (Button) findViewById(R.id.btnAssign);

		chosenSoldiers = new ArrayList<Soldier>();
		dutyList = new ArrayList<Duty>();
	}

	void setupTabHost() {
		OptionTabHost = (TabHost) findViewById(R.id.tabhost);
		OptionTabHost.setup();

		TabSpec specs = OptionTabHost.newTabSpec("tag From");
		specs.setContent(R.id.FromTab);
		specs.setIndicator("From");
		OptionTabHost.addTab(specs);

		specs = OptionTabHost.newTabSpec("tag To");
		specs.setContent(R.id.ToTab);
		specs.setIndicator("To");
		OptionTabHost.addTab(specs);

		specs = OptionTabHost.newTabSpec("tag When");
		specs.setContent(R.id.WhenTab);
		specs.setIndicator("When");
		OptionTabHost.addTab(specs);

		specs = OptionTabHost.newTabSpec("tag Who");
		specs.setContent(R.id.WhoTab);
		specs.setIndicator("Who");
		OptionTabHost.addTab(specs);

	}

	private void setupTabFunctionality() {

		OptionTabHost.getTabWidget().getChildAt(2)
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {

						Log.w("in setup tab", "2");
						handleHourList();
					}
				});

		OptionTabHost.getTabWidget().getChildAt(3)
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {

						Log.w("in setup tab", "3");
						handleSoldiersForDuty();
					}
				});
	}

	@SuppressWarnings("deprecation")
	private void handleHourList() {

		int fromHour = fromTime.getCurrentHour();
		int fromMinute = fromTime.getCurrentMinute();
		int toHour = toTime.getCurrentHour();
		int toMinute = toTime.getCurrentMinute();

		int fromDay = fromDate.getDayOfMonth();
		int fromMonth = fromDate.getMonth();

		int toDay = toDate.getDayOfMonth();
		int toMonth = toDate.getMonth();

		int year = calendar.get(Calendar.YEAR);
		Date fromDate = new Date(year, fromMonth, fromDay, fromHour, fromMinute);
		Date toDate = new Date(year, toMonth, toDay, toHour, toMinute);

		long diff = toDate.getTime() - fromDate.getTime();
		int diff_in_hours = (int) (diff / 1000 / 60 / 60);

		String[] dutyHours = null;
		if (diff_in_hours > 0) {
			dutyHours = new String[diff_in_hours + 1];
			for (int i = 0; i < dutyHours.length; i++) {
				dutyHours[i] = DutyDate.BuildReadableDate(fromDate, toDate);

				addDutyToDutyList(fromDate, toDate);

				fromDate.setHours(fromDate.getHours() + 2);
				toDate.setHours(toDate.getHours() + 2);

			}
		}

		hourList.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.activity_list_item, dutyHours));
	}

	private void addDutyToDutyList(Date fromDate, Date toDate) {

		switch (dutyType) {
		case Duty.GuardDuty: {
			dutyList.add(new GuardDuty(fromDate, toDate));
		}

		case Duty.KitchenDuty: {
			dutyList.add(new KitchenDuty(fromDate, toDate));
		}

		}

	}

	private void handleSoldiersForDuty() {

		SoldierList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		soldierMap = new HashMap<Integer, Soldier>();

		// load team
		Team team = SavingAndLoadingCenter.loadTeam();

		String[] teamNames = new String[team.getTeamSize()];
		int index = 0;
		for (Soldier s : team.getSoldiers()) {
			teamNames[index++] = s.getName() + " " + s.getLastName();
			soldierMap.put(index, s);
		}

		SoldierList.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_multiple_choice, teamNames));

		btnCheckAll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				for (int i = 0; i < SoldierList.getAdapter().getCount(); i++) {
					SoldierList.setItemChecked(i, true);
				}
			}
		});

		btnClearAll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				for (int i = 0; i < SoldierList.getAdapter().getCount(); i++) {
					SoldierList.setItemChecked(i, false);
				}
			}
		});

		btnAssign.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent assigningIntent = new Intent(getBaseContext(),
						ServiceType.class);

				// to pass :
				try {
					assigningIntent.putExtra("Assignment", prepareAssignment());
				} catch (NotEnoughParticipantsException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				startActivity(assigningIntent);

			}

		});

		SoldierList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int item,
					long id) {
				Soldier s = soldierMap.get(item);
				if (chosenSoldiers.contains(s)) {
					chosenSoldiers.remove(s);
				} else {
					chosenSoldiers.add(s);
				}
			}

		});

	}

	private Assignment prepareAssignment()
			throws NotEnoughParticipantsException {
		Service service = new Service();

		return ServiceManager.assignDuties(chosenSoldiers, service);
	}

	// display current time
	public void setCurrentTimeOnView() {

		// tvDisplayTime = (TextView) findViewById(R.id.tvTime);

		hour = calendar.get(Calendar.HOUR_OF_DAY);
		minute = calendar.get(Calendar.MINUTE);

		// set current time into time picker
		fromTime.setCurrentHour(hour);
		fromTime.setCurrentMinute(minute);

		toTime.setCurrentHour(hour);
		toTime.setCurrentMinute(minute);

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			// set time picker as current time
			return new TimePickerDialog(this, timePickerListener, hour, minute,
					false);

		}
		return null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.service_settings, menu);
		return true;
	}

}
